//
//  ImageParser.m
//  FootPrint
//
//  Created by alex tao on 4/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "ImageParser.h"
#import "CustomedImageRequest.pb.h"

@implementation ImageParser

- (void) uploadImage:(UIImage*)img
{
    if (nil == img) {
        [_delegate didUploadImage:nil];
        return;
    }
    
    NSData * imgData = UIImageJPEGRepresentation(img, 1.0);
    NSString * imgStr = [[[NSString alloc] initWithData:imgData encoding:NSASCIIStringEncoding] autorelease];

    ImageMessage * imgMsg = [[[[[[ImageMessage builder] setId:0] setIsSys:NO] setBinaryData:imgStr] setSuffix:@"jpeg"] build];
    
    CustomedImageRequestMessage_Builder * builder = [[[CustomedImageRequestMessage builder] setUserId:[GConfig getUserId]] setImage:imgMsg];
    
    NSData * queryData = [[builder build] data];
    if (queryData) {
        [super noCacheRequestURL:URL_UEER_IMAGE postData:queryData completion:^(NSData * resultData) {
            @try {
                CustomedImageResponseMessage * resp = [CustomedImageResponseMessage parseFromData:resultData];
                if (resp.resultCode == 0 && resp.imageId > 0) {
                    [[ImageManager sharedInstance] addImage:img forImageId:resp.imageId];
                } else {
                    [[[iToast makeText:@"上传图片失败!"] setDuration:2000] show];
                }
                [_delegate didUploadImage:resp];
            }
            @catch (NSException *e) {
                [[[iToast makeText:@"上传图片失败!"] setDuration:2000] show];
                [_delegate didUploadImage:nil];
            }
        } fail:^(NSError * err) {
            [[[iToast makeText:@"网络不给力!"] setDuration:2000] show];
            [_delegate didUploadImage:nil];
        }];
    }
}

@end
